<?php

class Lin_Request
{
	private static $instance;
	private $_modelName	= URL_MODEL_SIGN;
	private $_modelValue	= DEFAULT_MODEL;
	private $_controllerName	= URL_CONTROLLER_SIGN;
	private $_controllerValue	=  DEFAULT_CONTROLLER;
	private $_actionName	= URL_ACTION_SIGN;
	private $_actionValue	= DEFAULT_ACTION;
	private $_args = array();
	
	public static function getInstance()
	{
		if (self::$instance instanceof self)
		{
			return self::$instance;
		}
		else
		{
			self::$instance = new self();
			return self::$instance;
		} 
	}
	
	private function __construct()
	{
		$this->gets();
	}
	
	public function getModelName()
	{
		return $this->_modelName;
	}
	
	public function getModel()
	{
		return $this->_modelValue;
	}
	
	public function getControllerName()
	{
		return $this->_controllerName;
	}
	
	public function getController()
	{
		return $this->_controllerValue;
	}
	
	public function getActionName()
	{
		return $this->_actionName;
	}
	
	public function getAction()
	{
		return $this->_actionValue;
	}
	
	public function getArgs()
	{
		return $this->_args;
	}
	
	/**
	 * 
	 * 获取 URI
	 */
	public function getUri()
	{
		return $_SERVER['REQUEST_URI'];
	}
	
	/**
	 * 
	 * 获取控制器，模块，方法的名称
	 */
	private function gets()
	{
		if (isset($_GET[$this->_modelName]) && $tmp = trim($_GET[$this->_modelName]))
		{
			$this->_modelValue = $tmp;	
		}
		
		if (isset($_GET[$this->_controllerName]) && $tmp = trim($_GET[$this->_controllerName]))
		{
			$this->_controllerValue = $tmp;
		}
		
		if (isset($_GET[$this->_actionName]) && $tmp = trim($_GET[$this->_actionName]))
		{
			$this->_actionValue = $tmp;
		}
		
		$requestUri = $_SERVER['REQUEST_URI'];
		$redirect = $this->getRedirect($requestUri);
		
		if ($redirect && strstr($redirect, '/') && $redirect != '/')
		{
			$tmp = explode('/', $redirect);
			if ($tmp[0] == '')
			{
				array_shift($tmp);
			}
			$this->_args = $tmp;			
			$this->_modelValue =  isset($tmp[0]) && $tmp ? $tmp[0] : $this->_modelValue;
			$this->_controllerValue = isset($tmp[1]) && $tmp[1] ? $tmp[1] : $this->_controllerValue;
			$this->_actionValue = isset($tmp[2]) && $tmp[2] ? $tmp[2] : $this->_actionValue;		
		}	
			
	}
	
	/**
	 * 获取ReDirect
	 */
	private function getRedirect($requestUri)
	{
		$redirect = $requestUri;
		//先去掉index.php
		if ($tmp = stristr($requestUri,'/index.php'))
		{
			$redirect = substr($requestUri,10);
		}
		
		//去掉?号后部分
		$tmp = strpos($redirect, '?');
		if ($tmp !== false)
		{
			$redirect = substr($redirect, 0, $tmp);
		}
		
		return $redirect;
	}
}